import Vue from 'vue'
import Router from 'vue-router'
import SelectArea from "../view/AreaModule"
import LoginModle from "../view/LoginAndRegisterModule"
import Home from "../view/HomeModule"
import AdminModule from "../view/AdminModule/AdminModule"
import PersonalCenter from "../view/PersonalCenterModule"
import to404 from "../components/404"
import RentalModule from "../view/RentalModule";
import axios from "axios";

Vue.use(Router)
const view = function (name) {
  return () => import(`../view/AdminModule/${name}.vue`)
}


const globalRoutes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    name: 'Home',
    meta: {
      title: '主页',
      keepAlive: true
    }
  },
  {
    path:'/rentalList',
    component: RentalModule,
    name:'rentalList'
  },
  {
    path: '/personalCenter',
    component: PersonalCenter,
    name: 'PersonalCenter'
  },
  {
    path: '/to404',
    component: to404,
    name: 'to404',
  },
  {
    path: '/selectArea',
    name: 'SelectArea',
    component: SelectArea
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginModle
  },
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/AdminModule',
  component: AdminModule,
  name: 'AdminModule',
  // redirect: '/AdminModule',
  meta: {
    title: '主入口整体布局',
    roles: ["ROLE_ENTERADMIN"],
  },
  children:[],
  beforeEnter(to, from, next) {
    let token = localStorage.getItem('Authorization')
    if (!token || !/\S/.test(token)) {
      this.$store.dispatch("logout")
      next({name: 'Login'})
    }
    next()
  }
}


const router = new Router({
  mode: 'history',
  scrollBehavior: () => ({y: 0}),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes)
})


router.beforeEach((to, from, next) => {
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
    next()
  } else {
    let roleStr = sessionStorage.getItem("roleList")
    let roleList = roleStr.split(",")
    let isTo = false;
    roleList.forEach(item => {
      if (["ROLE_JUNIORADMIN"].indexOf(item) > -1) {
        isTo = true
      }
    })
    if (!isTo) {
      Vue.prototype.$message({
        type: "error",
        message: "未授权！"
      });
    } else {
      axios({
        url: '/getMenu',
        method: 'get',
      }).then(res => {
        console.log(123)
        if (res.data.code === 200) {
          fnAddDynamicMenuRoutes(res.data.data)
          router.options.isAddDynamicMenuRoutes = true
          sessionStorage.setItem('menuList', JSON.stringify(res.data.data || '[]'))
          next({...to, replace: true})
        } else {
          sessionStorage.setItem('menuList', '[]')
          next()
        }
      }).catch((e) => {
        console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
        router.push({name: 'Login'})
      })
    }

  }

})

function fnCurrentRouteType(route, globalRoutes = []) {
  var temp = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'AdminModule'
}


function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {

    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
    } else if (menuList[i].menuUrl && /\S/.test(menuList[i].menuUrl)) {

      menuList[i].menuUrl = menuList[i].menuUrl.replace(/^\//, '')
      var route = {
        path: menuList[i].menuUrl.replace('/', '-'),
        component: null,
        name: menuList[i].menuUrl.replace('/', '-'),
        meta: {
          // roles: ["ROLE_ENTERADMIN"],
          menuId: menuList[i].id,
          title: menuList[i].menuName,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      try {
        // () => import(`@/views${url }`)
        route['component'] =  view(menuList[i].menuUrl)
        // route['component'] =  () => import(`../view/AdminModule/${menuList[i].menuUrl}.vue`)

      } catch (e) {
        console.log("e====>",e)
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'AdminModule'
    mainRoutes.children = routes
    router.addRoutes([
      mainRoutes,
      { path: '*', redirect: { name: 'to404' } }
    ])
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
    console.log('\n')
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    console.log(mainRoutes.children)
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }

}

export default router
